438. 找到字符串中所有字母异位词
为保证权益,题目请参考 438. 找到字符串中所有字母异位词(From LeetCode).
解决方案1
Python
python
# 438. 找到字符串中所有字母异位词
# https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
from typing import List
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s):
return []
pl = [0] * 26
for pt in p:
pl[ord(pt) - ord("a")] += 1
ans = []
sl = pl.copy()
for i in range(len(p)):
sl[ord(s[i]) - ord("a")] -= 1
isOK = True
for i in range(26):
if sl[i] != 0:
isOK = False
break
if isOK:
ans.append(0)
for i in range(len(p), len(s)):
sl[ord(s[i]) - ord("a")] -= 1
sl[ord(s[i - len(p)]) - ord("a")] += 1
isOK = True
for j in range(26):
if sl[j] != 0:
isOK = False
break
if isOK:
ans.append(i - len(p) + 1)
return ans
if __name__ == "__main__":
solution = Solution()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44